package com.yisu.expressway.onedollar.activity;

import java.util.List;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.will.network.images.round.CircleImageView;
import com.yisu.expressway.R;
import com.yisu.expressway.onedollar.model.RecordHistoryItem;
import com.yisu.expressway.onedollar.presenter.IRecordHistoryPresenter;
import com.yisu.expressway.onedollar.presenter.impl.RecordHistoryPresenterImp;
import com.yisu.expressway.onedollar.view.IRecordHistoryView;
import com.yisu.expressway.onedollar.widget.TitleView;
import com.yisu.expressway.ui.recyclerview.BaseRvAdapter;
import com.yisu.expressway.ui.recyclerview.DividerListItemDecoration;
import com.yisu.expressway.ui.recyclerview.PagingRecyclerView;
import com.yisu.expressway.ui.refresh.SuperSwipeRefreshLayout;
import com.yisu.expressway.utils.SpannableUtil;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by shijunfeng on 2016/12/14.
 * 往期揭晓列表
 */
public class RecordHistoryListActivity extends BasicActivity
        implements IRecordHistoryView, PagingRecyclerView.SampleActionListener {
    private static final String EXTRA_KEY_GOODS_BARCODE = "extra_key_goods_barcode";
    @Bind(R.id.title_bar)
    protected TitleView mTitleView;
    @Bind(R.id.refreshLayout)
    protected SuperSwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.rv_content)
    protected PagingRecyclerView mCommodityListRv;
    @Bind(R.id.empty)
    protected View mEmptyView;
    @Bind(R.id.empty_iv)
    protected ImageView mEmptyIv;
    @Bind(R.id.empty_action)
    protected TextView mEmptyActionTv;
    @Bind(R.id.empty_des)
    protected TextView mEmptyDesTv;
    private IRecordHistoryPresenter mPresenter;
    private ImageView carImage;
    private AnimationDrawable mAnimation;
    private boolean isFreshEnable;
    private long mGoodsBarcode;

    public static void launch(Context context, long barcode) {
        Intent intent = new Intent(context, RecordHistoryListActivity.class);
        intent.putExtra(EXTRA_KEY_GOODS_BARCODE, barcode);
        context.startActivity(intent);
    }

    @Override
    protected int getThemeId() {
        return R.style.OneDollarTheme;
    }

    @Override
    protected int getInflateLayoutId() {
        return R.layout.activity_onedollar_record_history;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new RecordHistoryPresenterImp(this, this);
        mPresenter.init();
    }

    @Override
    protected void releasePresenter() {
        if (mPresenter != null) {
            mPresenter = null;
        }
    }

    @Override
    protected void getIntentData(Intent intent) {
        long longExtra = intent.getLongExtra(EXTRA_KEY_GOODS_BARCODE, -1);
        if (longExtra < 0) {
            finish();
            return;
        }
        mGoodsBarcode = longExtra;
    }

    @Override
    protected void getSavedBundleData(Bundle bundle) {

    }

    @Override
    protected void initViews() {
        initFreshLayout();
        DividerListItemDecoration mListDivider = new DividerListItemDecoration(this,
                LinearLayoutManager.VERTICAL, 6, R.color.colorLineGrey);
        mCommodityListRv.init(mListDivider, new LinearLayoutManager(this), this, 20);
    }

    @Override
    protected void bindEvents() {
        mTitleView.setOnTitleBarClickEvent(new TitleView.OnTitleBarClickEvent() {
            @Override
            public void onLeftClick(View view) {
                finish();
            }

            @Override
            public void onTitleClick(View view) {

            }

            @Override
            public void onRightClick(View view) {

            }
        });
    }

    @Override
    protected boolean isNeedLogin() {
        return false;
    }

    @Override
    protected void onLoginStateChange(boolean login) {

    }

    @Override
    public void showToast(String toastMsg) {
        if (StringUtil.isNullOrEmpty(toastMsg)) {
            return;
        }
        ToastUtil.displayLongToastMsg(this, toastMsg);
    }

    @Override
    public void showLoadingDlg() {
        showLoading();
    }

    @Override
    public void dismissLoadingDlg() {
        dismissLoading();
    }

    private View createHeaderView() {
        View headerView = getLayoutInflater().inflate(R.layout.layout_head, null);
        carImage = (ImageView) headerView.findViewById(R.id.pb_view);
        return headerView;
    }

    private void initFreshLayout() {
        mRefreshLayout.setHeaderViewBackgroundColor(0xffefeff4);
        mRefreshLayout.setHeaderView(createHeaderView());
        mRefreshLayout.setTargetScrollWithLayout(true);
        mRefreshLayout
                .setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

                    @Override
                    public void onRefresh() {
                        if (mAnimation != null) {
                            mAnimation.start();
                        }

                        mCommodityListRv.refreshData();
                    }

                    @Override
                    public void onPullDistance(int distance) {
                        int index = distance / 25;

                        int resId = R.drawable.car_1;
                        switch (index) {
                            case 2:
                                resId = R.drawable.car_2;
                                break;
                            case 3:
                                resId = R.drawable.car_3;
                                break;
                            case 4:
                                resId = R.drawable.car_4;
                                break;
                            case 5:
                                resId = R.drawable.car_5;
                                break;
                            case 6:
                                resId = R.drawable.car_6;
                                break;
                            case 7:
                                resId = R.drawable.car_7;
                                break;
                            case 8:
                                resId = R.drawable.car_8;
                                break;
                            case 9:
                                resId = R.drawable.car_9;
                                break;
                            case 10:
                                resId = R.drawable.car_10;
                                break;
                        }
                        if (!isFreshEnable) {
                            carImage.setBackgroundResource(resId);
                        }

                    }

                    @Override
                    public void onPullEnable(boolean enable) {
                        isFreshEnable = enable;
                        if (enable) {
                            carImage.setBackgroundResource(R.color.colorTransparent);
                            carImage.setImageResource(R.drawable.car_frame);
                            mAnimation = (AnimationDrawable) carImage.getDrawable();
                        }
                    }
                });

    }

    @Override
    public void fetchData(int start, int pageSize) {
        mPresenter.fetchMore(mGoodsBarcode, start, pageSize);
    }

    @Override
    public BaseRvAdapter.SampleViewHolder createItemViewHolder(ViewGroup parent, int viewType) {
        View itemView = getLayoutInflater().inflate(R.layout.onedollar_record_item_list, null);
        return new RecordViewHolder(itemView);
    }

    @Override
    public void bindData(BaseRvAdapter.SampleViewHolder _holder, int position, Object _item) {
        final RecordViewHolder holder = (RecordViewHolder) _holder;
        final RecordHistoryItem item = (RecordHistoryItem) _item;

        String goodspic = item.userHeadImg;
        if (!TextUtils.isEmpty(goodspic)) {
            String[] split = goodspic.split(",");
            if (split.length > 0) {
                String picShow = split[0];
                Glide.with(getApplicationContext()).load(picShow).asBitmap()
                        .placeholder(R.drawable.avatar_default)
                        .diskCacheStrategy(DiskCacheStrategy.ALL).centerCrop()
                        .animate(R.anim.fade_in_image).into(holder.mCoverIv);
            }
        } else {
            holder.mCoverIv.setImageDrawable(getResources().getDrawable(R.drawable.avatar_default));
        }
        String source = String.format(getResources().getString(R.string.one_dollar_winner),
                item.userName);
        holder.mWinnerTv.setText(SpannableUtil.setHighLight(this, source, source.substring(0, 5),
                R.color.oneDollarTextGrey));
        source = String.format(getResources().getString(R.string.one_dollar_userid),
                item.userAccount);
        holder.mUserIdTv.setText(SpannableUtil.setHighLight(this, source, source.substring(0, 5),
                R.color.oneDollarTextGrey));
        source = String.format(getResources().getString(R.string.one_dollar_join_num),
                item.joinNum);
        holder.mJoinNumTv.setText(SpannableUtil.setHighLight(this, source, source.substring(0, 6),
                R.color.oneDollarTextGrey));
        source = String.format(getResources().getString(R.string.one_dollar_luck_num),
                item.luckyNum);
        holder.mLuckNumTv.setText(SpannableUtil.setHighLight(this, source, source.substring(0, 5),
                R.color.oneDollarTextGrey));
        source = String.format(getResources().getString(R.string.one_dollar_periods_num_1),
                item.periodsNum);
        holder.mPeriodsNumTv.setText(source);
        source = String.format(getResources().getString(R.string.one_dollar_announced_time),
                item.announcedTime);
        holder.mAnnouncetimeTv.setText(source);
    }

    @Override
    public void refreshView(boolean bSuc) {
        mEmptyIv.setVisibility(View.GONE);
        mEmptyActionTv.setVisibility(View.GONE);
        mEmptyDesTv.setText(getString(R.string.one_dollar_empty_ordershow));
        if (bSuc){
            List<RecordHistoryItem> recordList = mPresenter.getRecordList();
            if (recordList == null || recordList.isEmpty()) {
                mRefreshLayout.setVisibility(View.GONE);
                mEmptyView.setVisibility(View.VISIBLE);
            }else {
                mRefreshLayout.setVisibility(View.VISIBLE);
                mEmptyView.setVisibility(View.GONE);
                mCommodityListRv.dataFetchDone(recordList);
            }

        }else {
            mRefreshLayout.setVisibility(View.GONE);
            mEmptyView.setVisibility(View.VISIBLE);
        }
        if (mAnimation != null) {
            mRefreshLayout.setRefreshing(false);
            mAnimation.stop();
            carImage.setImageResource(R.color.colorTransparent);
        }
    }

    class RecordViewHolder extends BaseRvAdapter.SampleViewHolder {

        @Bind(R.id.iv_cover)
        CircleImageView mCoverIv;
        @Bind(R.id.tv_winner)
        TextView mWinnerTv;
        @Bind(R.id.tv_user_id)
        TextView mUserIdTv;
        @Bind(R.id.tv_joinnum)
        TextView mJoinNumTv;
        @Bind(R.id.tv_luckNumber)
        TextView mLuckNumTv;
        @Bind(R.id.tv_periodsnum)
        TextView mPeriodsNumTv;
        @Bind(R.id.tv_record_announcetime)
        TextView mAnnouncetimeTv;

        public RecordViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
